<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/4/15
 * Time: 9:30
 */

namespace app\api\controller;


use think\Db;

class Friend extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 搜索、添加好友
     * @return \think\response\Json
     * phone_ID     搜索条件    手机号/ID
     */
    public function searchUser(){
        $phone_ID = input('phone_ID'); // 搜索条件  手机号/ID
        $list = Db::table('up_u_user')
            ->field('user_id, user_username, user_image')
            ->where('user_phone|user_create_id', 'like', '%' . $phone_ID . '%')
            ->where('user_status', 1)
            ->order('user_time desc')
            ->select();
        if($list){
            foreach($list as $k => $v){
                $friend = Db::table('up_friend')
                    ->where('f_my_id', $this->user_id)
                    ->where('f_friend_id', $v['user_id'])
                    ->find();
                if($friend){
                    $list[$k]['friend_status'] = $friend['f_status'];
                }else{
                    $list[$k]['friend_status'] = 4;
                }
            }
            
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 是否已申请过好友
     * @return \think\response\Json
     * other_user    被添加用户ID
     */
    public function isFriend(){
        $other_user = input('other_user');
        $already = Db::table('up_friend')
            ->where('f_my_id', $this->user_id)
            ->where('f_friend_id', $other_user)
            ->find();
        if($already){
            $is_apply = 1; // 已经申请过
        }else{
            $is_apply = 2; // 没有申请过
        }
        return json(['status' => 200, 'msg' => $is_apply]);
    }
    
    /**
     * 好友状态
     * @return \think\response\Json
     * other_user    好友ID
     */
    public function isBlack(){
        $other_user = input('other_user');
        $friend = Db::table('up_friend')
            ->where('f_my_id', $this->user_id)
            ->where('f_friend_id', $other_user)
            ->field('f_status')
            ->find();
        return json(['status' => 200, 'msg' => $friend]);
    }
    
    /**
     * 申请添加好友
     * @return \think\response\Json
     * other_user       被申请的用户ID
     * remark_name      备注
     * apply_info       申请验证信息
     */
    public function applyFriend(){
        $other_user = input('other_user'); // 被申请的用户ID
        $remark_name = trim(input('remark_name'), ' '); // 备注
        $apply_info = trim(input('apply_info'), ' '); // 申请验证信息
        if($other_user == $this->user_id){
            return json(['status' => 0, 'msg' => '不能添加自己为好友']);
        }
        $friend = [
            'f_my_id' => $this->user_id,
            'f_friend_id' => $other_user,
            'f_remark_name' => $remark_name,
            'f_apply_info' => $apply_info,
            'f_time' => $this->create_time
        ];
        // 如果被申请的用户已经申请了我，那么就直接通过
        $already = Db::table('up_friend')
            ->where('f_my_id', $other_user)
            ->where('f_friend_id', $this->user_id)
            ->find();
        $friend_info = Db::table('up_friend')
            ->where('f_my_id', $this->user_id)
            ->where('f_friend_id', $other_user)
            ->field('f_status')
            ->find();
        if($friend_info['f_status'] == 4){
            return json(['status' => 0, 'msg' => '该用户已被拉入黑名单，请从黑名单中移除']);
        }
        
        Db::startTrans();
        try{
            if($already){
                $update['f_status'] = 2;
                if($already['f_del'] == 2){
                    $update['f_del'] = 1;
                }
                Db::table('up_friend')->where('f_id', $already['f_id'])->update($update);
                $friend['f_status'] = 2;
            }
            Db::table('up_friend')->insert($friend);
            Db::commit();
            $list = [];
            try{
                array_push($list, (string)$other_user);
                $this->Jpush(1, $list, $apply_info, ['send_type' => 4]);
//                $this->Jpush1(1, $list, $apply_info, 4);
            }catch(\Exception $e){
                
            }
            return json(['status' => 200, 'msg' => '申请成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => '申请失败']);
        }
    }
    
    /**
     * 好友列表
     * @return \think\response\Json
     * keyword    查询关键字
     */
    public function friendList(){
        $keyword = input('keyword');
        $where['f_my_id'] = $this->user_id;
        $where['f_status'] = 2;
        if(isset($keyword) && $keyword != ''){
            $where['f_remark_name|user_username'] = ['like', '%' . $keyword . '%'];
        }
        // 新朋友数量
        $newFriend_num = Db::table('up_friend')
            ->where('f_friend_id', $this->user_id)
            ->where('f_status', 'IN', [1,2])
            ->where('f_del', 1)
            ->count();
        // 好友列表
        $friendList = Db::table('up_friend')
            ->join('up_u_user', 'user_id = f_friend_id', 'left')
            ->where($where)
            ->field('f_id, user_image, user_username, f_remark_name, f_friend_id')
//            ->order('f_time desc')
            ->select();
        if($friendList){
            foreach($friendList as $k => $v){
                if(empty($v['f_remark_name'])){
                    $friendList[$k]['f_remark_name'] = $v['user_username'];
                }
                // 字母排序
                $friendList[$k]['letter'] = $this->Getzimu($friendList[$k]['f_remark_name']);
            }
            $new_names = array_column($friendList, 'letter');
            array_multisort($new_names, SORT_ASC, $friendList);
            $start = '';
            $res = array();
            foreach ($friendList as $k => $v) {
                if ($v['letter'] != $start) {
                    $start = $v['letter'];
                }
                $res[$start][] = $v;
            }
            $jing = array();
            if(isset($res['#'])){
                $jing['#'] = $res['#'];
                unset($res['#']);
            }
            $friendList = array_merge($res,$jing);
            return json(['status' => 200, 'msg' => $friendList, 'newFriend_num' => $newFriend_num]);
        }else{
            return json(['status' => 200, 'msg' => [], 'newFriend_num' => $newFriend_num]);
        }
    }
    
    /**
     * 已拉黑好友列表
     * @return \think\response\Json
     * keyword    查询关键字
     */
    public function friendBlackList(){
        $keyword = input('keyword');
        $where['f_my_id'] = $this->user_id;
        $where['f_status'] = 4;
        if(isset($keyword) && $keyword != ''){
            $where['f_remark_name|user_username'] = ['like', '%' . $keyword . '%'];
        }
        // 好友列表
        $friendList = Db::table('up_friend')
            ->join('up_u_user', 'user_id = f_friend_id', 'left')
            ->where($where)
            ->field('f_id, user_image, user_username, f_remark_name, f_friend_id')
//            ->order('f_time desc')
            ->select();
        if($friendList){
            foreach($friendList as $k => $v){
                if(empty($v['f_remark_name'])){
                    $friendList[$k]['f_remark_name'] = $v['user_username'];
                }
            }
            return json(['status' => 200, 'msg' => $friendList]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 拉黑
     * @return \think\response\Json
     * other_user_id    被拉黑的人
     */
    public function joinBlack(){
        $other_user_id = input('other_user_id');
        $res = Db::table('up_friend')
            ->where('f_my_id', $this->user_id)
            ->where('f_friend_id', $other_user_id)
            ->setField('f_status', 4);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 取消拉黑
     * @return \think\response\Json
     * other_user_id    撤销黑名单的用户
     */
    public function cancelBlack(){
        $other_user_id = input('other_user_id');
        $res = Db::table('up_friend')
            ->where('f_my_id', $this->user_id)
            ->where('f_friend_id', $other_user_id)
            ->setField('f_status', 2);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 好友列表（无字母排序）
     * @return \think\response\Json
     * keyword    查询关键字
     */
    public function friendListNoSort(){
        $keyword = input('keyword');
        $where['f_my_id'] = $this->user_id;
        $where['f_status'] = 2;
        if(isset($keyword) && $keyword != ''){
            $where['f_remark_name|user_username'] = ['like', '%' . $keyword . '%'];
        }
        // 好友列表
        $friendList = Db::table('up_friend')
            ->join('up_u_user', 'user_id = f_friend_id', 'left')
            ->where($where)
            ->field('f_id, user_image, user_username, f_remark_name, f_friend_id')
            ->order('f_time desc')
            ->select();
        if($friendList){
            foreach($friendList as $k => $v){
                if(empty($v['f_remark_name'])){
                    $friendList[$k]['f_remark_name'] = $v['user_username'];
                }
                // 字母排序
//                $friendList[$k]['letter'] = $this->Getzimu($friendList[$k]['f_remark_name']);
            }
//            $new_names = array_column($friendList, 'letter');
//            array_multisort($new_names, SORT_ASC, $friendList);
//            $start = '';
//            $res = array();
//            foreach ($friendList as $k => $v) {
//                if ($v['letter'] != $start) {
//                    $start = $v['letter'];
//                }
//                $res[$start][] = $v;
//            }
//            $jing = array();
//            if(isset($res['#'])){
//                $jing['#'] = $res['#'];
//                unset($res['#']);
//            }
//            $friendList = array_merge($res,$jing);
            return json(['status' => 200, 'msg' => $friendList]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 设置好友备注
     * @return \think\response\Json
     * f_id     好友申请记录ID
     * remark_name    备注名
     */
    public function setRemark(){
        $f_id = input('f_id');
        $remark_name = input('remark_name');
        $res = Db::table('up_friend')->where('f_id', $f_id)->update(['f_remark_name' => $remark_name]);
        if($res){
            return json(['status' => 200, 'msg' => '设置成功']);
        }else{
            return json(['status' => 0, 'msg' => '设置失败']);
        }
    }
    
    /**
     * 删除好友
     * @return \think\response\Json
     * other_user    需要删除的好友ID
     */
    public function delFriend(){
        $other_user = input('other_user');
        Db::startTrans();
        try{
            Db::table('up_friend')
                ->where('f_my_id', $this->user_id)
                ->where('f_friend_id', $other_user)
                ->delete();
            Db::table('up_friend')
                ->where('f_my_id', $other_user)
                ->where('f_friend_id', $this->user_id)
                ->delete();
            Db::commit();
            return json(['status' => 200, 'msg' => '删除成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 新朋友列表
     * @return \think\response\Json
     * phone_ID     用户手机号/生成的ID
     */
    public function newFriendList(){
        $phone_ID = input('phone_ID');
        $where['f_del'] = 1;
        $where['f_friend_id'] = $this->user_id;
        $where['f_status'] = ['IN', [1,2]];
        if(isset($phone_ID) && !empty($phone_ID)){
            $where['user_phone|user_create_id'] = ['like', '%' . $phone_ID . '%'];
        }
        $list = Db::table('up_friend')
            ->join('up_u_user', 'user_id = f_my_id', 'left')
            ->where($where)
            ->field('user_username, user_image, user_id, f_apply_info, f_status, f_id')
            ->order('f_time desc')
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 新朋友数量
     * @return \think\response\Json
     */
    public function newFriendNum(){
        $where['f_del'] = 1;
        $where['f_friend_id'] = $this->user_id;
        $where['f_status'] = 1;
        $count = Db::table('up_friend')->where($where)->count();
        if($count){
            return json(['status' => 200, 'msg' => $count]);
        }else{
            return json(['status' => 200, 'msg' => 0]);
        }
    }
    
    /**
     * 接受好友请求
     * @return \think\response\Json
     * f_id    请求记录ID
     */
    public function agreeApply(){
        $f_id = input('f_id');
        $friend = Db::table('up_friend')
            ->where('f_id', $f_id)
            ->field('f_my_id')
            ->find();
        $insert = [
            'f_my_id' => $this->user_id,
            'f_friend_id' => $friend['f_my_id'],
            'f_status' => 2,
            'f_time' => $this->create_time
        ];
        Db::startTrans();
        try{
            Db::table('up_friend')->where('f_id', $f_id)->setField('f_status', 2);
            Db::table('up_friend')->insert($insert);
            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 删除新朋友
     * @return \think\response\Json
     * f_id    好友申请记录ID
     */
    public function delNewFriend(){
        $f_id = input('f_id');
        $res = Db::table('up_friend')->where('f_id', $f_id)->setField('f_del', 2);
        if($res){
            return json(['status' => 200, 'msg' => '删除成功']);
        }else{
            return json(['status' => 0, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 是不是好友
     * @return \think\response\Json
     * other_user_id  其他用户ID
     */
    public function alreadyFriend(){
        $other_user_id = input('other_user_id');
        $friend = Db::table('up_friend')
            ->where('f_my_id', $this->user_id)
            ->where('f_friend_id', $other_user_id)
            ->field('f_status')
            ->find();
        $friend1 = Db::table('up_friend')
            ->where('f_my_id', $other_user_id)
            ->where('f_friend_id', $this->user_id)
            ->field('f_status')
            ->find();
        if($friend['f_status'] == 2 && $friend1['f_status'] == 2){ // 互为好友，并且没有任意一方拉黑
            $already = 1; // 可以聊天
        }else{
            $already = 2; // 不可以聊天
        }
        return json(['status' => 200, 'msg' => $already]);
    }
    
    /**
     * 好友头像/昵称
     * @return \think\response\Json
     * other_user_id   其他用户ID
     */
    public function friendInfo(){
        $other_user_id = input('other_user_id');
        $user = Db::table('up_u_user')
            ->where('user_id', $other_user_id)
            ->field('user_username, user_image')
            ->find();
        // 好友备注
        $friend = Db::table('up_friend')
            ->where('f_my_id', $this->user_id)
            ->where('f_friend_id', $other_user_id)
            ->where('f_status', 2)
            ->field('f_remark_name')
            ->find();
        if($friend['f_remark_name']){
            $user['user_username'] = $friend['f_remark_name'];
        }
        
        return json(['status' => 200, 'msg' => $user]);
    }
    
    /**
     * 首字母
     * @param $str
     * @return string
     */
    public function Getzimu($str)
    {
        if(empty($str)){
            return '#';
        }
        $fchar = mb_substr($str, 0, 1, 'utf-8');
        // 判断表情    表情长度为4位
        if(strlen($fchar) >= 4 ){
            return '#';
        }
//        print_r(ord('z'));die;
//        $fchar=ord($str{0});
        if(ord($fchar) >= ord('A') && ord($fchar) <= ord('z')){
            return strtoupper($fchar);
        }
        $s1 = iconv('UTF-8', 'GBK', $str);
        $s2 = iconv('GBK', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0})*256+ord($s{1})-65536;
        if($asc >= -20319 && $asc <= -20284) return 'A';
        if($asc >= -20283 && $asc <= -19776) return 'B';
        if($asc >= -19775 && $asc <= -19219) return 'C';
        if($asc >= -19218 && $asc <= -18711) return 'D';
        if($asc >= -18710 && $asc <= -18527) return 'E';
        if($asc >= -18526 && $asc <= -18240) return 'F';
        if($asc >= -18239 && $asc <= -17923) return 'G';
        if($asc >= -17922 && $asc <= -17418) return 'H';
        if($asc >= -17417 && $asc <= -16475) return 'J';
        if($asc >= -16474 && $asc <= -16213) return 'K';
        if($asc >= -16212 && $asc <= -15641) return 'L';
        if($asc >= -15640 && $asc <= -15166) return 'M';
        if($asc >= -15165 && $asc <= -14923) return 'N';
        if($asc >= -14922 && $asc <= -14915) return 'O';
        if($asc >= -14914 && $asc <= -14631) return 'P';
        if($asc >= -14630 && $asc <= -14150) return 'Q';
        if($asc >= -14149 && $asc <= -14091) return 'R';
        if($asc >= -14090 && $asc <= -13319) return 'S';
        if($asc >= -13318 && $asc <= -12839) return 'T';
        if($asc >= -12838 && $asc <= -12557) return 'W';
        if($asc >= -12556 && $asc <= -11848) return 'X';
        if($asc >= -11847 && $asc <= -11056) return 'Y';
        if($asc >= -11055 && $asc <= -10247) return 'Z';
        return "#";
    }
}